/**
 * Globaljs
 *
 * Main script file for the theme
 *
 * @package Editr
 * @author Syamil MJ
 */

jQuery(document).ready(function($) {

    // Remove no-js class
    $('html').removeClass('no-js').addClass('js');

    var hasTouch = false,
        hasHistory = false;

    if (("ontouchstart" in document.documentElement)) {
        document.documentElement.className += " touch";
        hasTouch = true;
    }

    var isiPad = navigator.userAgent.match(/iPad/i) != null;

    // overrride prettyDate's text
    var pdmsg = aqvars.prettyDateMsg;

    $.prettyDate.messages = {
        now: pdmsg.now,
        minute: pdmsg.minute,
        minutes: $.prettyDate.template(pdmsg.minutes),
        hour: pdmsg.hour,
        hours: $.prettyDate.template(pdmsg.hours),
        yesterday: pdmsg.yesterday,
        dayBeforeYesterday: pdmsg.dayBeforeYesterday,
        days: $.prettyDate.template(pdmsg.days),
        week: pdmsg.week,
        weeks: $.prettyDate.template(pdmsg.weeks),
        month: pdmsg.month,
        months: $.prettyDate.template(pdmsg.months),
        year: pdmsg.year,
        years: $.prettyDate.template(pdmsg.years)
    }; 

    /** StreamApp */
    var StreamModel = Backbone.Model.extend({
        defaults: {
            thumbnail: '',
            timestamp: '',
            date: '',
            current: 0
        }
    });

    var StreamCollection = Backbone.Collection.extend({

        model: StreamModel,

        sort_key: '',

        initialize: function() {

        },

        comparator: function(item) {
            return -item.get(this.sort_key);
        },

        sortByField: function(fieldName) {
            this.sort_key = fieldName;
            this.sort();
        },

        pagination : function(perPage, page) {
            page = page - 1;
            var collection = this;
            collection = _(collection.rest(perPage*page));
            collection = _(collection.first(perPage));    
            return collection.map( function(model) { return model.toJSON() } );
        }

    });

    var Streams = new StreamCollection;

    var StreamView = Backbone.View.extend({

        tagName: 'li',

        template: _.template($('#stream-item-template').html()),

        initialize: function() {
            this.prettifyDate();
            this.currentItem = this.current();
        },

        prettifyDate: function() {
            var prettyDate = $.prettyDate.format(this.model.get('timestamp'));
            if( typeof prettyDate !== "undefined") { 
                this.model.set("date", prettyDate);
            }
        },

        current: function(model) {
            var current_id = $('body.single-post article.post').data('postid');
            if(this.model.get('post_id') == current_id) {
                this.model.set("date", 'Currently reading');
                return 'current';
            } else {
                return null;
            }
        },

        render: function(type) {
            var model = this.model.toJSON();
            this.$el.html(this.template(model));
            this.$el.wrap(this.tagName);
            this.$el.addClass(this.currentItem);
            this.$el.data('url', model.permalink)
            return this;
        }

    });
    

    var StreamApp = Backbone.View.extend({

        el: $('#stream'),

        tagName: 'li',

        perPage: aqoptions.streamsPerPage,

        page: 1,

        sortBy: aqoptions.defaultSortBy,

        category: 0, // category id

        loadingIcon: '<div class="loading"><span class="fontello-spin2 icon-spin"></span></div>',

        items: document.createDocumentFragment(),

        fixScrollerCount: 1,

        events: {
            "click .load-more": "loadMore",
            "click .stream-tab": "loadOnce",
            "mouseover .viewport": "showScrollbar",
            "mouseleave .viewport": "hideScrollbar",
            "touchstart .viewport": "showScrollbar",
            "touchend .viewport": "hideScrollbar",
            "click #stream-categories": "toggleCatPanel",
            "click .item": "gotolink"
        },

        initialize: function() {
            _.bindAll(this, 'fixStreamScrollTop', 'fixViewportHeight', 'streamScroller', 'loadOnce');
            var self = this;
            this.fixStreamScrollTop();
            this.fixViewportHeight();
            this.loadData();
            $(document).on('scroll', self.fixStreamScrollTop);
            $(window).on('resize', _.debounce( self.fixViewportHeight, 200) );
            
        },

        activeTab: function(event) {
            this.$el.find('.stream-tab').removeClass('active');
            $(event.currentTarget).addClass('active');
        },

        loadData: function() {

            var self = this;

            this.loadStart();

            $.ajax({
                url: aqvars.ajaxurl,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'get_streamlist',
                    page: 1
                },
                success: function(data, textStatus, xhr) {
                    Streams.add(data);
                    self.loadOnce();
                    self.loadComplete();
                }
            });

        },

        // Add a single stream item.
        addOne: function(stream, i) {
            var view = new StreamView({model: stream});
            var item = view.render().el;

            this.items = $(this.items).append(item);
        },

        loadItems: function() {

            this.page = this.page + 1;
            collection = new Backbone.Collection( Streams.pagination(this.perPage, this.page) );
            collection.each(this.addOne, this);

            this.render();
            this.streamScroller(true);

        },

        loadMore: function() {
            this.loadItems();
            nextCollection = new Backbone.Collection( Streams.pagination(this.perPage, this.page + 1) );

            if(!nextCollection.length) {
                this.$el.find('.load-more').remove();
            }

            return false;
        },

        loadOnce: function(event) {

            if(typeof event !== 'undefined') {
                this.sortBy = $(event.currentTarget).data('tabid');
                this.activeTab(event);
            }

            if(this.sortBy === 'popular') {
                Streams.sortByField('comments');
            } else {
                Streams.sortByField('unix');
            }

            this.page = 1; // reset pagenum

            collection = new Backbone.Collection( Streams.pagination(this.perPage, this.page) );
            collection.each(this.addOne, this);

            this.render(true);

            nextCollection = new Backbone.Collection( Streams.pagination(this.perPage, this.page + 1) );
            this.$el.find('.load-more').remove();
            if(nextCollection.length) this.moreButton();

            this.streamScroller();
            
        },

        // loads all items from previous page
        loadPast: function() {
            if(this.sortBy === 'popular') Streams.sortByField('comments');
            collection = new Backbone.Collection( Streams.first(this.perPage * 2) );
            collection.each(this.addOne, this);

            nextCollection = new Backbone.Collection( Streams.pagination(this.perPage, this.page + 1) );
            if(nextCollection.length) this.moreButton();
        },

        moreButton: function() {
            var loadMoreButton = '<a class="load-more" href="#">'+ aqvars.loadMoreStreamstxt +'<i class="icon-refresh"></i></a>';
            this.$el.find('#stream-list ul').after(loadMoreButton);
        },

        render: function(replace) {
            if(replace == true) {
                this.$el.find('#stream-list ul').html(this.items);
            } else {
                this.$el.find('#stream-list ul').append(this.items);
            }
        },

        fixStreamScrollTop: function() {

            var intScrollTop = $("html").scrollTop() || $("body").scrollTop(),
                headerHeight = $('#header').outerHeight();

            if( intScrollTop >= headerHeight ) {
                this.$el.addClass('fixed');
            } else {
                this.$el.removeClass('fixed');
            }

        },

        fixViewportHeight: function() {

            var windowHeight = $(window).height(),
                wpadminbarHeight = $('#wpadminbar').outerHeight(),
                streamtabsHeight = $('#stream-tabs').outerHeight(),
                padding = 20;

            var totalHeight = wpadminbarHeight + padding + streamtabsHeight;

            var viewportHeight = windowHeight - totalHeight;

            if(hasTouch) {
                viewportHeight = windowHeight - 40;
            }

            if(isiPad) {
                viewportHeight = viewportHeight - 50;
            }

            this.$el.find('.viewport').css('height', viewportHeight + 'px');

            if(this.fixScrollerCount > 1) {
                this.streamScroller(true);
            } else {
                this.streamScroller();
            }

            this.fixScrollerCount = this.fixScrollerCount + 1;
            
        },

        streamScroller: function(update) {

            if(update) {
                this.$el.tinyscrollbar_update('relative');
            } else {
                var options = {
                    invertscroll: function() {
                        if(hasTouch) return true;
                    },
                    lockscroll: false
                }
                this.$el.tinyscrollbar(options);
            }

        },

        showScrollbar: function() {
            this.$el.find('.scrollbar').fadeIn();
        },

        hideScrollbar: function() {
            this.$el.find('.scrollbar').fadeOut();
        },

        loadStart: function() {

            this.$el.append(this.loadingIcon);
            this.$el.find('.load-more i').addClass('icon-spin');

        },

        loadComplete: function() {

            this.$el.find('.loading').fadeOut( function() { $(this).remove() });
            this.$el.find('.load-more i').removeClass('icon-spin');
            
        },

        toggleCatPanel: function() {
            var panel = this.$el.find('.categories-panel');
            panel.slideToggle(100);
        },

        gotolink: function() {
            return false;
        }

    });

    /** $LoadMore app */
    var LoadMoreRouter = Backbone.Router.extend({

        routes: {
            "page/:number" : "load" 
        },

        default: function() {
            // do nothin
        },

        load: function(data) {
            // do nothin
        }

    });

    var Router = new LoadMoreRouter;

    var LoadMoreApp = Backbone.View.extend({
        
        el: $('#main'),

        page: 1,

        autoLoadRunning: false,

        autoLoadThreshold: aqoptions.autoLoadThreshold,

        maxNumPages: $('.article-list').data('max_num_pages'),

        loadingButton: '<div class="loading">Loading <span class="fontello-spin2 icon-spin"></span></div>',

        loadMoreButton: '<div id="load-more"><a href="#" class="btn">'+ aqvars.loadMorePoststxt + '</a></div>',

        events: {
            "click #load-more": "loadMore"
        },

        initialize: function() {

            _.bindAll(this, 'autoLoad', 'loadMore', 'getPosts', 'update');
            var self = this;
            
            $(document).on('scroll', _.debounce( self.autoLoad, 200 ) );

        },

        autoLoad: function() {

            var windowHeight = $(window).height(),
                intScrollTop = $("html").scrollTop() || $("body").scrollTop(),
                documentHeight = $(document).height(),
                footerHeight = $('#footer').outerHeight(),
                listBottom;

            listBottom = documentHeight - windowHeight - intScrollTop;

            if(listBottom > footerHeight) return false;

            if(this.page >= this.autoLoadThreshold) return false;

            this.getPosts();

        },

        loadMore: function() {

            var self = this;

            this.$el.find('#load-more').css('display', 'none');
            self.$el.find('.loading').fadeIn('200');
            this.getPosts();
            return false;
        },

        getPosts: function() {
            
            var self = this;

            // run only if function is not already running
            if(!this.autoLoadRunning) {

                this.autoLoadRunning = true;

                this.$el.append(this.loadingButton);

                var url = aqvars.home_url + '/page/' + (this.page + 1) + '/';

                var jqxhr = $.get(url, this.update).fail(this.fail);
                
            }
            
        },

        update: function(data) {

            if(!data) {
                return false;
            }

            var articleList = this.$el.find('.article-list'),
                articles = $(data).find('.article-list').html();
            
            this.$el.find('.loading').fadeOut().remove();

            if(this.page == this.maxNumPages) {
                articleList.after(articles);
            } else {
                var $newItems = $(articles).hide();
                articleList.append( $newItems ).isotope('appended', $newItems);
                $newItems.show();
            }

            this.page = this.page + 1;
            this.autoLoadRunning = false;

            // show featured image
            articleList.trigger('loadMore');

            if(this.page == this.autoLoadThreshold) {
                articleList.after(this.loadMoreButton);
            }

            if(this.page > this.autoLoadThreshold && this.page <= this.maxNumPages) {
                this.$el.find('#load-more').fadeIn();
            }

            Router.navigate('page/' + this.page + '/', {trigger: true});

        },

        fail: function(data) {
            alert('No more posts to load!');
        }

    });

    /** $Global app */
    var GlobalApp = Backbone.View.extend({

        el: $(document),

        initialize: function() {
            self = this;
            window.addEventListener("load", function(){ if(!window.pageYOffset){ self.hideAddressBar(); } } );
            window.addEventListener("orientationchange", this.hideAddressBar );
            if(!aqvars.is_page) $Stream = new StreamApp;
            
            //load more posts
            if(aqoptions.loadMore && !aqvars.is_paged && aqvars.is_home) {
                $LoadMore = new LoadMoreApp;
                hasHistory = true;
            }

            $('.comment-form-fields').hide();
            $('.comment-date').prettyDate();
            this.initIsotope();
            this.demoTime();
            this.responsiveVideos();
            this.flexslider();
            this.showFeaturedImage();
            this.dropdownMenu();
        },

        events: {
            "click .streambutton": "showStream",
            "focus #comment": "showCommentFields",
            "click .menubutton": "mobileMenu",
            "loadMore .article-list": "showFeaturedImage",
            "click #search-bar i": "toggleSearchBar"
        },

        showStream: function() {
            var Bar = $('#stream');

            if(Bar.hasClass('unfolded')) {
                Bar.removeClass('unfolded');
                Bar.css('margin-left', '-320px');
            } else {
                Bar.addClass('unfolded');
                Bar.css('margin-left', '0px');
            }
        },

        demoTime: function() {
            if(aqvars.demoMode) {
                $.prettyDate.now = function () {
                    var demoDate = new Date('2013, 05, 18').getTime();
                    return new Date("June 23, 2013 01:08:00");
                }
            }
        },

        hideAddressBar: function() {
          if(!window.location.hash)
          {
              if(document.height < window.outerHeight)
              {
                  document.body.style.height = (window.outerHeight + 50) + 'px';
              }
         
              setTimeout( function(){ window.scrollTo(0, 1); }, 50 );
          }
        },

        responsiveVideos: function() {
            if (jQuery().fitVids) {
                $("article").fitVids();
            };
        },

        flexslider: function() {
            if (jQuery().flexslider) {
                $('.flexslider').flexslider({
                    animation: "slide",
                    smoothHeight: true,
                });
            };
        },

        showFeaturedImage: function() {
            $('article.format-standard .featured img').each(function() {
                $(this).fadeIn().css('display', 'block');
            });
        },

        mobileMenu: function() {
            $('header nav').slideToggle();
        },
        
        dropdownMenu: function() {
            if(jQuery().hoverIntent) {
                $('nav#primary-nav > ul > li').hoverIntent({
                    over : function() { $(this).children('ul.sub-menu').slideDown().fadeIn(); },
                    out : function() { $(this).children('ul.sub-menu').slideUp().fadeOut(); },
                    timeout: 100
                });
            };
        },

        showCommentFields: function() {
            $('.comment-form-fields').slideDown();
        },

        toggleSearchBar: function() {
            $('#search-bar').toggleClass('active');
        },

        initIsotope: function() {

            if(jQuery().isotope) {

                var $container = $('.article-list');

                $container.isotope({
                    resizable: false,
                    masonry: { columnWidth: $container.width() / 2 },
                    queue: false
                });

                $(window).smartresize(function(){
                    $container.isotope({
                        masonry: { columnWidth: $container.width() / 2 }
                    });
                });

            }

        }


    });

    $App = new GlobalApp;

    if(hasHistory) {
        Backbone.history.start({root: aqvars.home_root, pushState: true});
    }

});